import { _decorator, AudioClip, AudioSource, Component, director, Node, sys } from "cc";
import { ScoreUI } from "./UI/ScoreUI";
import { Player } from "./Player";
import { GameOverUI } from "./UI/GameOverUI";
import { AudioMgr } from "./AudioMgr";
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
  private static _instance: GameManager = null;

  // 炸弹数量
  @property
  private bombNumber: number = 0;

  // 分数
  @property
  private score: number = 0;

  @property({ type: ScoreUI })
  scoreUI: ScoreUI = null;

  @property({ type: Player })
  player: Player = null;

  @property(Node)
  pauseButtonNode: Node = null;

  @property(Node)
  resumeButtonNode: Node = null;

  @property(GameOverUI)
  gameOverUI: GameOverUI = null;

  @property(AudioClip)
  gameMusic: AudioClip = null;

  @property(AudioClip)
  buttonAudio: AudioClip = null;

  @property(AudioClip)
  gameOverAudio: AudioClip = null;

  public static getInstance(): GameManager {
    return this._instance;
  }

  protected start(): void {
    AudioMgr.inst.play(this.gameMusic, 0.3);
  }

  protected onLoad(): void {
    GameManager._instance = this;
  }

  /** 增加炸弹数量 */
  public AddBomb() {
    this.bombNumber += 1;
    this.node.emit("onBombChange");
  }

  /** 增加分数 */
  public AddSocre(s: number) {
    this.score += s;
    this.scoreUI.onScoreChange(this.score);
  }

  /** 获取炸弹数量 */
  public GetBombNumber(): number {
    return this.bombNumber;
  }

  /** 暂停游戏 */
  onPauseButtonClick() {
    AudioMgr.inst.play(this.buttonAudio, 1);
    AudioMgr.inst.pause();
    director.pause();
    this.player.disableControl(false);
    this.pauseButtonNode.active = false;
    this.resumeButtonNode.active = true;
  }

  /** 继续游戏 */
  onResumeButtonClick() {
    AudioMgr.inst.play(this.buttonAudio, 1);
    AudioMgr.inst.resume();
    director.resume();
    this.player.disableControl(true);
    this.pauseButtonNode.active = true;
    this.resumeButtonNode.active = false;
  }

  /** 游戏结束 */
  gameOver() {
    AudioMgr.inst.play(this.gameOverAudio);
    let hScore = Number(localStorage.getItem("HighestScore") ?? this.score);

    if (this.score > hScore) {
      localStorage.setItem("HighestScore", this.score.toString());
      hScore = this.score;
    }
    // 暂停游戏
    this.onPauseButtonClick();
    // 显示游戏结束页面 更新分数
    this.gameOverUI.showGameOverUI(hScore, this.score);
  }

  // 重新开始
  onRestartButtonClick() {
    AudioMgr.inst.play(this.buttonAudio, 1);
    director.loadScene(director.getScene().name);
    this.onResumeButtonClick();
  }

  // 退出游戏
  onQuitButtonClick() {
    AudioMgr.inst.play(this.buttonAudio, 1);
  }

  isHaveBomb(): boolean {
    return this.bombNumber > 0;
  }

  useBomb() {
    if (this.bombNumber <= 0) return;
    this.bombNumber -= 1;
    this.node.emit("onBombChange");
  }
}
